import json

from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import status
from rest_framework.viewsets import ModelViewSet
from django_redis import get_redis_connection

from drf_shop_admin.settings import dev as settings
from users.serializers.user import UserInfoSerializer, UserSerializer
from users.models import User

class UserInfoAPIView(APIView):
    """
    get:
    当前用户信息

    当前用户信息, status: 200(成功), return: 用户信息和权限
    """
    def get(self, request: Request, *args, **kwargs):
        user_info = request.user.get_user_info()
        conn = get_redis_connection('user_info')
        user_info['permissions'] = json.dumps(user_info['permissions'])
        conn.hmset('user_info_%s' % request.user.id, user_info)
        conn.expire('user_info_%s' % request.user.id, settings.REDIS_TIMEOUT)
        user_info['permissions'] = json.loads(user_info['permissions'])

        return Response(user_info, status=status.HTTP_200_OK)

class UserInfoAPIView_1(APIView):
    """使用序列化器"""
    def get(self, request, *args, **kwargs):
        serializer = UserInfoSerializer(instance=request.user)
        conn = get_redis_connection('user_info')
        user_info = serializer.data
        user_info['permissions'] = json.dumps(user_info['permissions'])
        conn.hmset('user_info_%s' % request.user.id, user_info)
        conn.expire('user_info_%s' % request.user.id, settings.REDIS_TIMEOUT)
        user_info['permissions'] = json.loads(user_info['permissions'])

        return Response(serializer.data, status=status.HTTP_200_OK)

class UserModelViewSet(ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer


class ModifyUserStateAPIView(APIView):
    """
    修改用户状态
    """
    def put(self, request: Request, uid: int, type: int, *args, **kwargs):
        print(f'uid = {uid}, type = {type}')
        ret = {'msg': 'success', 'errors': '', 'code': '', 'data': ''}
        if type not in [0, 1]:
            ret['errors'] = '用户状态值有误，0或者1'
            return Response(ret, status=status.HTTP_404_NOT_FOUND)
        user = User.objects.get(id=uid)
        if not user:
            ret['errors'] = '用户id不存在'
            return Response(ret, status=status.HTTP_204_NO_CONTENT)
        user.is_active = type
        user.save()
        serializer = UserSerializer(instance=user)
        ret['data'] = serializer.data
        return Response(ret, status=status.HTTP_200_OK)